//
//  UserBookListViewController.swift
//  readmate
//
//  Created by fallen.ink on 01/07/2017.
//  Copyright © 2017 fallen.ink. All rights reserved.
//

import UIKit
import DisplaySwitcher
import SnapKit

// MARK: - Const define

private let animationDuration: TimeInterval = 0.3

private let listLayoutStaticCellHeight: CGFloat = 80
private let gridLayoutStaticCellHeight: CGFloat = 165

// MARK: - Class UserBookListScene

class UserBookListScene: _Scene, UICollectionViewDelegate, UICollectionViewDataSource, UISearchBarDelegate {
    
    var output: UserBookListInteractor?
    
    //
    fileprivate lazy var collectionView = UICollectionView(frame:CGRect(), collectionViewLayout: UICollectionViewLayout())
    fileprivate var searchBar = UISearchBar(frame: CGRect())
    fileprivate var rotationButton = SwitchLayoutButton()
    
    fileprivate var tap: UITapGestureRecognizer!
    fileprivate var users = UserDataProvider().generateFakeUsers()
    fileprivate var searchUsers = [User]()
    
    fileprivate var isTransitionAvailable = true
    fileprivate lazy var listLayout = DisplaySwitchLayout(staticCellHeight: listLayoutStaticCellHeight, nextLayoutStaticCellHeight: gridLayoutStaticCellHeight, layoutState: .list)
    fileprivate lazy var gridLayout = DisplaySwitchLayout(staticCellHeight: gridLayoutStaticCellHeight, nextLayoutStaticCellHeight: listLayoutStaticCellHeight, layoutState: .grid)
    fileprivate var layoutState: LayoutState = .list
    
    // MARK: - Life cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        
        searchUsers = users
        rotationButton.isSelected = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Initialize

    override func initView() {
        // Container
        self.title = "图书"
        self.view.backgroundColor = color_background_view;
        
        // NavigationBar
//        UIBarButtonItem barButtonItem = UIBar
        self.setRightNavigationBarButton(button: rotationButton, target: self, action: #selector(self.onListStyleTransition(_:)))
        
        // TableView
        
        // SearchBar
        searchBar.delegate = self;
        self.view.addSubview(searchBar)
        
        // CollectionView
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.white
        collectionView.collectionViewLayout = listLayout
        
//        collectionView.register(UserBookListCell.class, forCellWithReuseIdentifier: UserBookListCell.id)
        collectionView.register(UserBookListCell.cellNib, forCellWithReuseIdentifier: UserBookListCell.id)
        
        NSLog("%@", UserBookListCell.id)
        
        self.view.addSubview(collectionView)
        
        // Data
        
        
        // Network
    }
    
    override func makeConstraints() {
        rotationButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(18)
        }
        
        searchBar.snp.makeConstraints { (make) in
            make.height.equalTo(50)
            make.width.equalToSuperview()
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(searchBar.snp.bottom)
            make.bottom.equalTo(self.view.snp.bottom)
            make.width.equalToSuperview()
            make.centerX.equalToSuperview()
        }
    }
    
    // MARK: - Actions
    func onListStyleTransition(_ sender: AnyObject) {
        if !isTransitionAvailable {
            return
        }
        let transitionManager: TransitionManager
        if layoutState == .list {
            layoutState = .grid
            transitionManager = TransitionManager(duration: animationDuration, collectionView: collectionView, destinationLayout: gridLayout, layoutState: layoutState)
        } else {
            layoutState = .list
            transitionManager = TransitionManager(duration: animationDuration, collectionView: collectionView, destinationLayout: listLayout, layoutState: layoutState)
        }
        transitionManager.startInteractiveTransition()
        rotationButton.isSelected = layoutState == .list
        rotationButton.animationDuration = animationDuration
    }
    
    func tapRecognized() {
        view.endEditing(true)
    }

}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension UserBookListScene {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return searchUsers.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserBookListCell.id, for: indexPath) as! UserBookListCell
        if layoutState == .grid {
            cell.setupGridLayoutConstraints(1, cellWidth: cell.frame.width)
        } else {
            cell.setupListLayoutConstraints(1, cellWidth: cell.frame.width)
        }
        cell.bind(searchUsers[(indexPath as NSIndexPath).row])
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
        let customTransitionLayout = TransitionLayout(currentLayout: fromLayout, nextLayout: toLayout)
        return customTransitionLayout
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isTransitionAvailable = false
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        isTransitionAvailable = true
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
}

// MARK: - UISearchBar

extension UserBookListScene {
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty {
            searchUsers = users
        } else {
            searchUsers = searchUsers.filter { return $0.name.contains(searchText) }
        }
        
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Hi \((indexPath as NSIndexPath).row)")
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        view.addGestureRecognizer(tap)
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        view.removeGestureRecognizer(tap)
    }
    
    func handleTap() {
        view.endEditing(true)
    }
    
}

